package com.huazi.www.doctor.hu.util;

import java.sql.*;

public class BaseDao {
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf8";
    private static String userName = "root";
    private static String pwd = "123456";
    public Connection conn = null;
    public PreparedStatement ps = null;
    public ResultSet rs = null;

    /**
     * 连接
     *
     * @return
     */
    public Connection getConn() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(url, userName, pwd);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 通用增删改
     *
     * @param sql
     * @param ob
     * @return
     */
    public int getUpdate(String sql, Object... ob) {
        int count = 0;
        conn = getConn();
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < ob.length; i++) {
                ps.setObject(i + 1, ob[i]);
            }
            count = ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return count;
    }

    /**
     * 查询
     *
     * @param sql
     * @param ob
     * @return
     */
    public ResultSet executeQuery(String sql, Object... ob) {
        conn = getConn();
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < ob.length; i++) {
                ps.setObject(i + 1, ob[i]);
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return rs;
    }

    /**
     * 关闭
     *
     * @param conn
     * @param ps
     * @param rs
     */
    public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
